package com.hygj.realm;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.hygj.pojo.User;
import com.hygj.service.UserService;

public class ShiroRealm extends AuthorizingRealm {

	@Autowired
	private UserService userService;

	/**
	 * Shiro身份登录认证 原理： 1、用户提交 用户名和密码 --- 2、shiro 封装令牌 ---- 3、realm 通过用户名将密码查询返回
	 * ---- 4、shiro 自动去比较查询出密码和用户输入密码是否一致---- 5、进行登陆控制
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken)
			throws AuthenticationException {
		System.out.println("--------------开始身份认证----------------------");
		UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
		System.out.println("-----用户名：" + token.getUsername());
		System.out.println("-----密码：" + token.getPassword().toString());
		// 根据用户名去查找对象
		User user = userService.findUserByLoginName(token.getUsername());
		System.out.println(user);
		// MD5加密
		if (user != null) {
			// 把管理员信息存入到Sesion中
			SecurityUtils.getSubject().getSession().setAttribute("user", user);
			AuthenticationInfo info = new SimpleAuthenticationInfo(user.getUsername(),user.getPassword(), "");
			return info;
		} else {
			throw new AuthenticationException("用户不存在");
		}
	}

	/**
	 * 登录成功的 Shiro权限和角色认证
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
		// TODO Auto-generated method stub
		return null;
	}

}
